package fr.tocchisu.movies.services.db.mongoDB;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.Mongo;

import fr.tocchisu.movies.services.Movie;
import fr.tocchisu.movies.services.parsers.PlainTextMovieGenreInterfaceParser;

public class MovieGenreDBInit extends PlainTextMovieGenreInterfaceParser {
    private final static Logger LOGGER = LoggerFactory.getLogger(MovieGenreDBInit.class);

    private DB db;
    private DBCollection dbCollection;
    private final String hostname = "localhost";
    private final String dbName = "test";
    private String username;
    private String pwd;
    private int port;
    private final Map<String, Object> keyvalues = new HashMap<String, Object>();

    @Override
    protected void beforeFileParsed() {
	Mongo mongo = null;
	try {
	    mongo = new Mongo(hostname);
	} catch (Exception e) {
	    LOGGER.error(e.getMessage(), e);
	}
	db = mongo.getDB(dbName);
	if (StringUtils.isNotBlank(username))
	    db.authenticate(username, pwd.toCharArray());
	dbCollection = db.getCollection("movies");
    }

    @Override
    public void afterLineParsed(Movie movie) {
	DBObject query = new BasicDBObject();
	if (movie.getName() != null)
	    query.put("name", movie.getName());
	if (movie.getReleaseDate() != null)
	    query.put("releaseDate", movie.getReleaseDate());
	DBObject movieToUpdate = new BasicDBObject();
	movieToUpdate.putAll(query.toMap());
	movieToUpdate.put("genre", movie.getGenre().getName());
	dbCollection.findAndModify(query, movieToUpdate);
    }

    @Override
    protected void afterFileParsed() {
	db.getMongo().close();
    }

    public static void main(String[] args) {
	// try {
	// System.out.println("Please enter a hostname :");
	// System.in.read();
	// System.out.println();
	// System.out.println("Please enter a dbname :");
	// System.in.read();
	new MovieGenreDBInit().read();
	// } catch (IOException e) {
	// LOGGER.error(e.getMessage(), e);
	// }
    }
}
